<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <!-- <el-form-item label="上级ID" prop="parentId">
            <el-input v-model="queryParams.parentId" placeholder="请输入上级ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="类型：1闸机，2分析盒，3网络摄像头，4网络抓拍机，5视屏话机" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择类型：1闸机，2分析盒，3网络摄像头，4网络抓拍机，5视屏话机" clearable>
              <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="设备系列" prop="series">
            <el-select v-model="queryParams.series" placeholder="请选择设备系列" clearable>
              <el-option v-for="dict in device_series" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="设备IP" prop="ip">
            <el-input v-model="queryParams.ip" placeholder="请输入设备IP" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="唯一码" prop="guid">
            <el-input v-model="queryParams.guid" placeholder="请输入设备唯一码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="安装区域" prop="area">
            <el-select v-model="queryParams.area" placeholder="请选择安装区域" clearable>
              <el-option v-for="dict in device_area" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="安装位置" prop="location">
            <el-input v-model="queryParams.location" placeholder="请输入安装位置" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="安装方向" prop="position">
            <el-select v-model="queryParams.position" placeholder="请选择安装方向" clearable>
              <el-option v-for="dict in device_position" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="onlineStatus">
            <el-select v-model="queryParams.onlineStatus" placeholder="请选择状态" clearable>
              <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="最后在线时间" prop="offlineTime">
            <el-date-picker clearable v-model="queryParams.offlineTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择最后在线时间" />
          </el-form-item> -->
          <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="dict in use_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['device:deviceInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:deviceInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['device:deviceInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:deviceInfo:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="User" v-loading="buttonLoading" @click="handleBatchAddPerson" v-hasPermi="['device:mqtt:batchAddPerson']"
              >同步人员信息</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="Clock"
              :disabled="multiple"
              v-loading="buttonLoading"
              @click="handleAdStrategy()"
              v-hasPermi="['device:mqtt:updateStrategy']"
              >同步通行策略</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 420px)"
        stripe
        v-loading="loading"
        :data="deviceInfoList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row)=>handleDetail(row)"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <!-- <el-table-column label="上级ID" align="center" prop="parentId" /> -->
        <!-- <el-table-column label="类型：1闸机，2分析盒，3网络摄像头，4网络抓拍机，5视屏话机" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="device_type" :value="scope.row.type" />
          </template>
        </el-table-column> -->
        <el-table-column label="设备名称" align="center" prop="name" />
        <!-- <el-table-column label="设备系列" align="center" prop="series">
          <template #default="scope">
            <dict-tag :options="device_series" :value="scope.row.series" />
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="设备IP" align="center" prop="ip" /> -->
        <!-- <el-table-column label="设备编码" align="center" prop="deviceCode" />
        <el-table-column label="设备唯一码" align="center" prop="guid" /> -->
        <el-table-column label="安装区域" align="center" prop="area">
          <template #default="scope">
            <dict-tag :options="device_area" :value="scope.row.area" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="安装位置" align="center" prop="location" /> -->
        <el-table-column label="安装方向" align="center" prop="position">
          <template #default="scope">
            <dict-tag :options="device_position" :value="scope.row.position" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="onlineStatus">
          <template #default="scope">
            <dict-tag :options="online_status" :value="scope.row.onlineStatus" />
          </template>
        </el-table-column>
        <el-table-column label="最后在线时间" align="center" prop="offlineTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.offlineTime }}</span>
            <!-- <span>{{ parseTime(scope.row.offlineTime, '{y}-{m}-{d}') }}</span> -->
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <!-- <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="use_status" :value="scope.row.status" />
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:deviceInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:deviceInfo:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="一键重启" placement="top" v-if="scope.row.onlineStatus==1" v-hasPermi="['device:deviceInfo:restart']">
              <el-button link type="warning" class="btn" @click="handleRestartRequest(scope.row)">一键重启</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改人脸闸机对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="740px" append-to-body>
      <el-form ref="deviceInfoFormRef" :inline="true" :model="form" :rules="rules" label-width="100px" class="add-form">
        <!-- <el-form-item label="上级ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入上级ID" />
        </el-form-item> -->
        <!-- <el-form-item label="类型：1闸机，2分析盒，3网络摄像头，4网络抓拍机，5视屏话机" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型：1闸机，2分析盒，3网络摄像头，4网络抓拍机，5视屏话机">
            <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="设备系列" prop="series">
          <el-select v-model="form.series" placeholder="请选择设备系列">
            <el-option v-for="dict in device_series" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备UUID" prop="uuid">
          <el-input v-model="form.uuid" placeholder="请输入设备UUID" />
        </el-form-item>
        <el-form-item label="设备IP" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入设备IP" />
        </el-form-item>
        <el-form-item label="设备Mac" prop="mac">
          <el-input v-model="form.mac" placeholder="请输入设备MAC" />
        </el-form-item>
        <!-- <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备唯一码" prop="guid">
          <el-input v-model="form.guid" placeholder="请输入设备唯一码" />
        </el-form-item> -->
        <el-form-item label="设备账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入设备账号" />
        </el-form-item>
        <el-form-item label="设备密码" prop="userPassword">
          <el-input v-model="form.userPassword" placeholder="请输入设备密码C" />
        </el-form-item>
        <el-form-item label="安装区域" prop="area">
          <el-select v-model="form.area" placeholder="请选择安装区域">
            <el-option v-for="dict in device_area" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入安装位置" />
        </el-form-item>
        <el-form-item label="安装方向" prop="position">
          <el-select v-model="form.position" placeholder="请选择安装方向">
            <el-option v-for="dict in device_position" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="onlineStatus">
          <el-select v-model="form.onlineStatus" placeholder="请选择状态">
            <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="最后在线时间" prop="offlineTime">
          <el-date-picker clearable v-model="form.offlineTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择最后在线时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark" style="width: 95%">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in use_status" :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DeviceInfo" lang="ts">
import {
  listDeviceInfo,
  getDeviceInfo,
  delDeviceInfo,
  addDeviceInfo,
  updateDeviceInfo,
  batchAddPerson,
  restartRequest,
  addStrategy
} from '@/api/device/deviceInfo';
import { DeviceInfoVO, DeviceInfoQuery, DeviceInfoForm } from '@/api/device/deviceInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { device_type, device_position, use_status, device_series, device_area, online_status } = toRefs<any>(
  proxy?.useDict('device_type', 'device_position', 'use_status', 'device_series', 'device_area', 'online_status')
);

const deviceInfoList = ref<DeviceInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const deviceInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceInfoForm = {
  id: undefined,
  uuid: undefined,
  parentId: undefined,
  type: 0,
  name: undefined,
  series: 2,
  ip: undefined,
  deviceCode: undefined,
  guid: undefined,
  area: undefined,
  location: undefined,
  position: undefined,
  onlineStatus: 1,
  offlineTime: undefined,
  remark: undefined,
  mac: undefined,
  userName: undefined,
  userPassword: undefined,
  status: 1
};
const data = reactive<PageData<DeviceInfoForm, DeviceInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parentId: undefined,
    type: 0,
    name: undefined,
    series: undefined,
    ip: undefined,
    deviceCode: undefined,
    guid: undefined,
    area: undefined,
    location: undefined,
    position: undefined,
    onlineStatus: undefined,
    offlineTime: undefined,
    status: 1,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    uuid: [{ required: true, message: '设备UUID不能为空', trigger: 'blur' }],
    series: [{ required: true, message: '设备系列不能为空', trigger: 'change' }],
    // deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    // guid: [{ required: true, message: '设备唯一码不能为空', trigger: 'blur' }],
    area: [{ required: true, message: '安装区域', trigger: 'change' }],
    position: [{ required: true, message: '安装方向', trigger: 'change' }]
    // userName: [{ required: true, message: '设备账号不能为空', trigger: 'blur' }],
    // userPassword: [{ required: true, message: '设备密码不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询人脸闸机列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDeviceInfo(queryParams.value);
  deviceInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const selectItems = ref<Array<DeviceInfoVO>>([]);
/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selectItems.value = selection;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加人脸闸机';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDeviceInfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改人脸闸机';
};

/** 提交按钮 */
const submitForm = () => {
  deviceInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let tipText = '修改成功';
      if (form.value.id) {
        await updateDeviceInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        let tipText = '新增成功';
        await addDeviceInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess(tipText);
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceInfoVO) => {
  const _ids = row?.id || ids.value;
  let tipText = '是否确认删除选中的数据？';
  if (row?.id) {
    tipText = '是否确认删除"' + row.name + '"的数据项？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  await delDeviceInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'device/deviceInfo/export',
    {
      ...queryParams.value
    },
    `deviceInfo_${new Date().getTime()}.xlsx`
  );
};

const handleBatchAddPerson = async () => {
  await proxy?.$modal.confirm('是否下发人员信息至面板机？');
  buttonLoading.value = true;
  const res = await batchAddPerson([]).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess(`处理完成，本次下发人员数量：${res.data}`);
};

/** 重启设备 */
const handleRestartRequest = async (row?: DeviceInfoVO) => {
  let _ids = row?.id || ids.value;
  let tipText = '是否重启设备？';
  if (row?.id) {
    tipText = '是否重启"' + row.name + '"？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  if (!Array.isArray(_ids)) {
    _ids = [_ids];
  }
  await restartRequest(_ids);
  proxy?.$modal.msgSuccess('重启成功');
  await getList();
};

/** 更新通行策略 */
const handleAdStrategy = async (row?: DeviceInfoVO) => {
  let _ids = row?.id || ids.value;
  if (!Array.isArray(_ids)) {
    _ids = [_ids];
  }
  if (_ids.length == 0) {
    return proxy?.$modal.msgWarning('请选择设备');
  }
  for (const item of selectItems.value) {
    if (item.position == 2) {
      return proxy?.$modal.msgError('设备"' + item.name + '"为“出”方向，无需添加通行策略，请重新选择');
    }
  }
  let tipText = '是否更新所选设备通行策略？';
  if (row?.id) {
    tipText = '是否更新"' + row.name + '"的通行策略？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (buttonLoading.value = false));
  buttonLoading.value = true;
  const res = await addStrategy(_ids).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess(`更新完成，设备数量：${res.data.deviceCount}，添加通行策略数量：${res.data.strategyCount}`);
  await getList();
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.btn {
  border: 1px solid var(--el-color-warning) !important;
  border-radius: 20px;
  padding: 5px 10px;
}
</style>
